package l1j.opqlo.Timer.Controler;

import java.util.Collection;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.server.Thread.PcOtherThreadPool;
import l1j.server.echo.ClientThread;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_ChangeName;

/**
 * PC 死亡刪除處理 時間軸
 *
 * @author dexc
 *
 */
//@FunctionalInterface
public class PcDeleteTimer extends TimerTask {

	private static final Logger _log = Logger.getLogger(PcDeleteTimer.class
			.getName());

	/**
	 * 登出死亡角色
	 *
	 * @param tgpc
	 */
	private static void outPc(final L1PcInstance tgpc) {
		try {
			// 人物還在死亡狀態
			if (tgpc.isDead()) {
				final ClientThread client = tgpc.getNetConnection();
				// 改變顯示(復原正常)
				tgpc.sendPacketsAll(new S_ChangeName(tgpc.getId(), tgpc.getName()));
				client.close();
				_log.info("角色死亡登出: " + tgpc.getName());
				// 返回人物選取畫面
				// client.sendPacket(new S_PacketBoxSelect());
			}

		} catch (final Exception e) {
			_log.log(Level.WARNING, "登出死亡角色時發生異常!", e);
		}
	}

	private ScheduledFuture<?> _timer;

	@Override
	public void run() {
		try {
			final Collection<L1PcInstance> all = L1World.getInstance().getAllPlayers();
//			final Collection<L1PcInstance> all = L1World.getInstance().getAllPlayers().parallelStream()
//					.filter(L1PcInstance -> L1PcInstance.isDead())
//					.collect(java.util.stream.Collectors.toList());
//			// 不包含元素
//			if (all.isEmpty()) {
//				return;
//			}
//			final Collection<L1PcInstance> isdead = all.parallelStream()
//					.filter(L1PcInstance -> L1PcInstance.get_delete_time()>0)
//					.collect(java.util.stream.Collectors.toList());
//			
//			isdead.forEach(L1PcInstance -> L1PcInstance.set_delete_time(L1PcInstance.get_delete_time()-1));
//			
//			final Collection<L1PcInstance>outlist = isdead.parallelStream()
//					.filter(L1PcInstance -> L1PcInstance.get_delete_time()<=0)
//					.collect(java.util.stream.Collectors.toList());
//			
//			outlist.forEach(L1PcInstance -> outPc(L1PcInstance));
			
			for (final L1PcInstance tgpc : all) {
				if (!tgpc.isDead()) {
					continue;
				}

				if (tgpc.get_delete_time() <= 0) {
					continue;
				}
				final int newtime = tgpc.get_delete_time() - 1;
				tgpc.set_delete_time(newtime);
				if (tgpc.get_delete_time() <= 0) {
					outPc(tgpc);
				}
			}

		} catch (final Exception e) {
			_log.log(Level.SEVERE, "PC 死亡刪除處理時間軸異常重啟", e);
			PcOtherThreadPool.get().cancel(this._timer, false);
			final PcDeleteTimer pcHprTimer = new PcDeleteTimer();
			pcHprTimer.start();
		}
	}

	public void start() {
		final int timeMillis = 1100;// 1秒
		this._timer = PcOtherThreadPool.get().scheduleAtFixedRate(this,
				timeMillis, timeMillis);
	}
}